import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/pick/ai_model_logic.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/utils/date_time_utils.dart';
import 'package:sports_new/utils/mode_config.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/view/pick/ai/ai_type.dart';
import 'package:sports_new/view/pick/items/ai_lm_item.dart';
import 'package:sports_new/view/pick/items/ai_info_label.dart';
import 'package:sports_new/view/pick/items/ai_match_item.dart';
import 'package:sports_new/view/pick/items/rect_date_bar.dart';
import 'package:sports_new/widgets/loading/loading_indicator.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/loading/no_data_widget.dart';
import 'package:sports_new/widgets/scroll_bar.dart';
import 'package:visibility_detector/visibility_detector.dart';
import '../../../utils/routes.dart';
import '../../../utils/user.dart';
import '../../../widgets/base/qkd_text.dart';
import '../../../widgets/base/qkd_button.dart';
import '../items/ai_combo_item.dart';
import '../items/ai_plan_item.dart';
import '../items/banner_scaffold.dart';

class AiModelPage extends StatefulWidget {
  const AiModelPage({super.key});

  @override
  State<AiModelPage> createState() => _AiModelPageState();
}

class _AiModelPageState extends State<AiModelPage> {
  final AiModelLogic logic = Get.put(AiModelLogic(),
      tag: AiType.getTypeByRoute(Get.currentRoute)?.tag);

  @override
  Widget build(BuildContext context) {
    return GetBuilder<AiModelLogic>(
        tag: AiType.getTypeByRoute(Get.currentRoute)?.tag,
        builder: (logic) {
          return VisibilityDetector(
            key: const Key("ai_model"),
            onVisibilityChanged: (VisibilityInfo info) {
              if (!info.visibleBounds.isEmpty && logic.data != null) {
                logic.getRefresh();
              }
            },
            child: BannerScaffold(
                type: logic.type?.label ?? "",
                titleFade: true,
                backFade: false,
                needScroll: true,
                aboveFade: true,
                brightness: Brightness.light,
                bannerHeight:
                    logic.infoHeight + MediaQuery.of(context).padding.top + 12,
                aboveWidget: Column(
                  mainAxisAlignment: ModeConfig.aiRecord
                      ? MainAxisAlignment.end
                      : MainAxisAlignment.center,
                  children: [
                    Container(height: 20),
                    CachedNetworkImage(
                      height: 44,
                      imageUrl: logic.logo ?? "",
                      errorWidget: (context, url, error) =>
                          Container(height: 44),
                      placeholder: (context, url) => Container(),
                    ),
                    Container(height: 8),
                    QkdText(logic.name ?? "",
                        fontSize: 18,
                        color: Colours.white,
                        fontWeight: FontWeight.w500),
                    Container(height: 10),
                    QkdText(
                      logic.info ?? "",
                      color: Colours.white.withOpacity(0.7),
                      fontSize: 12,
                    ).paddingOnly(bottom: 10, left: 12, right: 12),
                    if (logic.aiInfo.hasValue && ModeConfig.aiRecord)
                      AiInfoLabel(
                        key: logic.infoKey,
                        type: logic.type,
                        data: logic.aiInfo,
                        rate: logic.aiInfoRate,
                      ).paddingOnly(bottom: 12),
                  ],
                ).paddingSymmetric(horizontal: 8),
                action: [
                  QkdButton(
                    onPressed: () =>
                        Get.toNamed(Routes.aiExample, arguments: logic.type),
                    text: "示例",
                    foregroundColor: Colours.white,
                    textStyle: const TextStyle(
                        fontSize: 14,
                        shadows: [BoxShadow(offset: Offset(0, 0.5))]),
                  )
                ],
                bodyTopWidget: dateBar(),
                body: (physics) => Stack(
                      alignment: AlignmentDirectional.center,
                      children: [
                        Column(
                          children: [
                            SizedBox(
                              width: Get.width,
                              child: ScrollBoard(
                                  margin:
                                      const EdgeInsets.fromLTRB(8, 12, 8, 0),
                                  type: logic.type?.route ?? ""),
                            ),
                            Expanded(
                                child: logic.infoHeight == 0
                                    ? const LoadingIndicator()
                                    : TabBarView(
                                        controller: logic.tabController,
                                        children: List.generate(
                                            logic.type == AiType.combo
                                                ? logic.comboList.length
                                                : logic.matchList.length,
                                            (index) => page(index, physics))))
                          ],
                        ),
                        Positioned(
                          bottom: 0,
                          left: 0,
                          right: 0,
                          child: _buyBottom(),
                        )
                      ],
                    )),
          );
        });
  }

  Widget dateBar() {
    return logic.infoHeight == 0
        ? Container()
        : RectDateBar.dark(
            margin: const EdgeInsets.symmetric(horizontal: 8),
            controller: logic.tabController,
            dateList: logic.dayList,
            showAbove: logic.showAllHit,
            labelAbove: Positioned(
                right: 0,
                top: 0,
                child: Image.asset(Utils.getImgPath("ai_all_hit.png"),
                    height: 31)),
          );
  }

  Widget page(int index, ScrollPhysics physics) {
    return LoadingWidget<int>(
      isLoading: logic.isLoading[index],
      data: logic.matchList[index].length + logic.comboList[index].length,
      child: () => Padding(
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: CustomScrollView(
          physics: physics,
          slivers: [
            SliverToBoxAdapter(
              child: DefaultTextStyle(
                style: const TextStyle(fontSize: 12, color: Colours.grey99),
                child: Row(
                  children: [
                    QkdText(logic.filterCount),
                    const Spacer(),
                    if (logic.type != AiType.plan)
                      GestureDetector(
                        onTap: () => logic.showDatePicker(),
                        child: Container(
                          key: ValueKey(index),
                          height: 24,
                          alignment: Alignment.center,
                          padding: const EdgeInsets.symmetric(horizontal: 5),
                          decoration: BoxDecoration(
                              border:
                                  Border.all(color: Colours.grey99, width: 0.5),
                              borderRadius: BorderRadius.circular(15)),
                          child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                QkdText(logic.filter,
                                    needCenter: true,
                                    fontSize: 12,
                                    color: Colours.grey66),
                                const SizedBox(width: 2),
                                Padding(
                                    padding: const EdgeInsets.only(top: 1),
                                    child: Image.asset(
                                        width: 6,
                                        Utils.getImgPath('down_arrow.png')))
                              ]),
                        ),
                      )
                  ],
                ),
              ).paddingSymmetric(horizontal: 8, vertical: 8),
            ),
            if (logic.comboList[index].isNotEmpty) ...[
              LoadingWidget<bool>(
                isLoading: logic.isLoading[index],
                loading: const SliverToBoxAdapter(),
                data: logic.comboList[index].isEmpty,
                noData: const NoDataWidget.sliver(),
                child: () {
                  var list = logic.comboList[index].where((e) {
                    switch (logic.filter) {
                      case "一级":
                        return e.items?.any((element) =>
                                logic.oneLevelId.contains(element.leagueId)) ??
                            false;
                      case "竞足":
                        return e.items
                                ?.any((element) => element.jcMatchNo != null) ??
                            false;
                      case "单场":
                        return e.items
                                ?.any((element) => element.dcMatchNo != null) ??
                            false;
                      case "十四场":
                        return e.items?.any(
                                (element) => element.sfcMatchNo != null) ??
                            false;
                      default:
                        return true;
                    }
                  }).toList();
                  return SliverList(
                      delegate: SliverChildListDelegate(list
                          .map((e) => AiComboItem(
                                item: e,
                                logic: logic,
                                onChange: (change) {
                                  if (change == true) logic.needReGet = 0;
                                },
                              ))
                          .toList()));
                },
              )
            ],
            if (logic.matchList[index].isNotEmpty) ...[
              LoadingWidget<bool>(
                isLoading: logic.isLoading[index],
                loading: const SliverToBoxAdapter(),
                data: logic.matchList[index].isEmpty,
                noData: const NoDataWidget.sliver(),
                child: () {
                  var list = logic.matchList[index].where((e) {
                    switch (logic.filter) {
                      case "一级":
                        return logic.oneLevelId.contains(e.leagueId);
                      case "竞足":
                        return e.jcMatchNo != null;
                      case "单场":
                        return e.dcMatchNo != null;
                      case "十四场":
                        return e.sfcMatchNo != null;
                      default:
                        return true;
                    }
                  }).toList();
                  return SliverList(
                      delegate: SliverChildListDelegate(list.map((e) {
                    if (logic.type == AiType.plan) {
                      return AiPlanItem(
                        item: e,
                        ticketName: logic.ticketName(e),
                        onChange: (change) {
                          if (change == true) logic.needReGet = 0;
                        },
                      );
                    } else if (logic.type == AiType.lm) {
                      return AiLmItem(
                        item: e,
                        ticketName: logic.ticketName(e),
                        onChange: (change) {
                          if (change == true) logic.needReGet = 0;
                        },
                      );
                    } else {
                      return AiMatchItem(
                        item: e,
                        type: logic.type,
                        ticketName: logic.ticketName(e),
                        onChange: (change) {
                          if (change == true) logic.needReGet = 0;
                        },
                      );
                    }
                  }).toList()));
                },
              )
            ],
            if (logic.notHitList[index].hasValue) ...[
              LoadingWidget<bool>(
                isLoading: logic.isLoading[index],
                loading: const SliverToBoxAdapter(),
                data: logic.notHitList[index].isEmpty,
                noData: const NoDataWidget.sliver(),
                child: () {
                  var list = logic.notHitList[index].where((e) {
                    switch (logic.filter) {
                      case "一级":
                        return logic.oneLevelId.contains(e.leagueId);
                      case "竞足":
                        return e.jcMatchNo != null;
                      case "单场":
                        return e.dcMatchNo != null;
                      case "十四场":
                        return e.sfcMatchNo != null;
                      default:
                        return true;
                    }
                  }).toList();
                  return SliverList(
                      delegate: SliverChildListDelegate(list.map((e) {
                    if (logic.type == AiType.plan) {
                      return AiPlanItem(
                        item: e,
                        ticketName: logic.ticketName(e),
                        onChange: (change) {
                          if (change == true) logic.needReGet = 0;
                        },
                      );
                    } else if (logic.type == AiType.lm) {
                      return AiLmItem(
                        item: e,
                        ticketName: logic.ticketName(e),
                        onChange: (change) {
                          if (change == true) logic.needReGet = 0;
                        },
                      );
                    } else {
                      return AiMatchItem(
                        item: e,
                        type: logic.type,
                        ticketName: logic.ticketName(e),
                        onChange: (change) {
                          if (change == true) logic.needReGet = 0;
                        },
                      );
                    }
                  }).toList()));
                },
              )
            ],
            SliverToBoxAdapter(child: Container(height: 80))
          ],
        ),
      ),
    );
  }

  Widget _buyBottom() {
    return Padding(
      padding: EdgeInsets.fromLTRB(
          12, 0, 12, 24 + MediaQuery.of(context).padding.bottom),
      child: Stack(
        children: [
          Container(
            height: 48,
            alignment: Alignment.center,
            clipBehavior: Clip.antiAlias,
            decoration: BoxDecoration(
                color: Colours.white,
                borderRadius: BorderRadius.circular(24),
                boxShadow: [
                  BoxShadow(
                      color: const Color(0xFF8692A4).withOpacity(0.41),
                      blurRadius: 12,
                      offset: const Offset(0, 2))
                ]),
            child: Column(
              children: [
                Container(
                  padding: const EdgeInsets.only(left: 16, right: 4),
                  height: 48,
                  child: Row(
                    children: [
                      if (logic.price?.length != 0)
                        Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                QkdText(
                                  "${logic.realPrice ?? ""}球币".changeUnit,
                                  color: Colours.main,
                                  fontSize: 16,
                                  fontWeight: FontWeight.w500,
                                  height: 1.4,
                                ),
                                if (logic.price != logic.realPrice)
                                  QkdText(
                                    "${logic.price ?? ""}球币".changeUnit,
                                    decoration: TextDecoration.lineThrough,
                                    fontSize: 10,
                                    color: Colours.grey99,
                                    height: 1.4,
                                  ).paddingOnly(left: 4),
                              ],
                            ),
                            if (logic.check?.endTime.hasValue == true)
                              QkdText(
                                  "到期时间：${DateTime.parse(logic.check!.endTime!).formatedString("yyyy-MM-dd")}",
                                  fontSize: 10,
                                  color: Colours.grey99)
                          ],
                        ),
                      const Spacer(),
                      GestureDetector(
                        onTap: () => User.needLogin(() {
                          Utils.onEvent('mx_ljkt');
                          Get.toNamed(Routes.aiPay,
                              arguments: logic.type,
                              parameters: {"roomId": "${logic.roomId ?? ""}"});
                        }),
                        child: Container(
                          padding: const EdgeInsets.symmetric(vertical: 4),
                          child: Container(
                              height: 40,
                              width: logic.price.toDouble() == 0 ? null : 108,
                              padding:
                                  const EdgeInsets.symmetric(horizontal: 16),
                              alignment: Alignment.center,
                              clipBehavior: Clip.antiAlias,
                              decoration: BoxDecoration(
                                  color: Colours.main,
                                  borderRadius: BorderRadius.circular(20)),
                              child: QkdText(
                                  logic.check?.isOpen != 1
                                      ? logic.price.toDouble() == 0
                                          ? "限时免费体验"
                                          : "立即开通"
                                      : "立即续费",
                                  color: Colors.white,
                                  fontWeight: FontWeight.w500)),
                        ),
                      ),
                    ],
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }
}
